﻿using System;
using System.Net;
using System.Threading.Tasks;
using RestSharp;

namespace WhallaToolkit.ShareServices.Helpers
{
    public static class RestClientExtensions
    {
        public static Task<string> GetContentAsync(this RestClient client, IRestRequest request)
        {
            return client.SelectAsync(request, response => response.Content);
        }

        public static Task<IRestResponse> GetResponseAsync(this RestClient client, IRestRequest request)
        {
            return client.SelectAsync(request, response => response);
        }

        private static Task<T> SelectAsync<T>(this RestClient client, IRestRequest request, Func<IRestResponse, T> selector)
        {
            var tcs = new TaskCompletionSource<T>();
            client.ExecuteAsync(
                request,
                response =>
                {
                    if (response.ErrorException != null)
                    {
                        tcs.SetException(response.ErrorException);
                    }
                    else if (response.ResponseStatus != ResponseStatus.Completed)
                    {
                        tcs.SetException(new WebException("Execution has failed with status " + response.ResponseStatus.ToString(), WebExceptionStatus.ReceiveFailure));
                    }
                    else if (response.StatusCode != HttpStatusCode.OK)
                    {
                        tcs.SetException(new WebException("Execution has failed with status code " + response.StatusCode.ToString(), WebExceptionStatus.UnknownError));
                    }
                    else
                    {
                        tcs.SetResult(selector(response));
                    }
                });
            return tcs.Task;
        }
    }
}
